package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.TDialogManager;
import com.ycsj.common.utils.MaxTextLengthFilter;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.Res;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.RvClassInfoAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.ClassInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.Group;
import com.ycsj.goldmedalnewconcept.teacher.bean.StudentInfo;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 班级信息
 * Created by Administrator on 2019/3/25 0025.
 */

public class TeacherClassInfoActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_add_student)
    ImageView lvAddStudent;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.tv_class_name)
    TextView tvClassName;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.rl_content)
    RelativeLayout rlContent;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    //传递的班级对象
    private ClassInfo.ListBean classInfo;

    //列表的适配器数据
    private List<Group> oldDatas;

    //列表适配器
    private RvClassInfoAdapter adapter;

    //已经使用的小组名称和头像的Icon集合
    private ArrayList<Integer> usedIcons;
    private ArrayList<String> usedNames;

    //班级
    private String classNum;

    //创建小组成功后界面刷新的标识
    public static final int CREATEGROUPSUCCESS = 0x660;

    //RecyclerView的脚布局
    private View footView;
    private ImageView addGroup;

    //班级的头像数组
    private int classHeads[] = {R.drawable.class1, R.drawable.class2, R.drawable.class3, R.drawable.class4, R.drawable.class5, R.drawable.class6,
            R.drawable.class7, R.drawable.class8, R.drawable.class9, R.drawable.class10};

    /**
     * 跳转到该页面的方法
     *
     * @param context
     * @param listBean 传递的班级对象
     */
    public static void goActivity(Context context, ClassInfo.ListBean listBean) {
        Intent it = new Intent(context, TeacherClassInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", listBean);
        it.putExtras(bundle);
        context.startActivity(it);
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_classinfo;
    }

    @Override
    protected void init() {
        //初始化状态栏
        initStateBar();

        //获取传递的班级对象并设置班级名称
        initIntent();

        //请求页面数据
        http(BqaManager.NORML);
    }

    /**
     * 设置班级的
     */
    private void initIntent() {
        classInfo = (ClassInfo.ListBean) getIntent().getSerializableExtra("data");
        if (null != classInfo) {
            classNum = classInfo.getNum() + "";
        }

        //设置班级名称
        if (null != classInfo) {
            tvClassName.setText(classInfo.getName());
        }

        //初始化使用过的Icons和Names
        usedIcons = new ArrayList<>();
        usedNames = new ArrayList<>();
    }

    /**
     * 请求页面数据
     */
    private void http(final int method) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "4");
        map.put("userID", AccountUtils.getAccount(this));
        map.put("classnum", classNum);

        LogUtils.iTag("test", HttpAddress.CLASSINFO + "?type=4&userID=" + AccountUtils.getAccount(this)
                + "&classnum=" + classNum);

        HttpUtils.post(HttpAddress.CLASSINFO, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                rlLoading.setVisibility(View.GONE);
                rlContent.setVisibility(View.GONE);
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String json, int id) {

                //将加载框关闭
                if (rlLoading.getVisibility() != View.GONE) {
                    rlLoading.setVisibility(View.GONE);
                }

                if (rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                if (method == BqaManager.NORML) {
                    //转换页面展示需要的数据
                    oldDatas = convertDatas(json);

                    //设置列表的数据
                    initRv();

                    //让添加学生的按钮显示出来
                    if (lvAddStudent.getVisibility() != View.VISIBLE) {
                        lvAddStudent.setVisibility(View.VISIBLE);
                    }

                } else if (method == BqaManager.PULLREFRESH) {
                    //创建小组成功后熟悉
                    oldDatas.clear();
                    oldDatas.addAll(convertDatas(json));
                    if (oldDatas.size() >= 10) {
                        if (footView != null) {
                            adapter.removeFooterView(footView);
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });

    }

    /**
     * 记录已经使用过的小组名称和头像
     */
    private void initHasUsedData() {
        usedIcons.clear();
        usedNames.clear();
        if (oldDatas != null) {
            for (int i = 0; i < oldDatas.size(); i++) {
                usedNames.add(oldDatas.get(i).name);
                usedIcons.add(oldDatas.get(i).icon);
            }
        }
    }

    /**
     * 初始化列表展示
     */
    private void initRv() {
        adapter = new RvClassInfoAdapter(this, R.layout.teacher_rv_team, oldDatas);
        footView = View.inflate(this, R.layout.rv_class_info_foot_view, null);
        addGroup = footView.findViewById(R.id.lv_add_group);
        addGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //添加小组的操作
                addGroupAction();
            }
        });

        if (null != oldDatas && oldDatas.size() < 10) {
            adapter.addFooterView(footView);
        }
        BqaManager.setRv(null, this, adapter, rv);
    }

    /**
     * 根据服务器返回的Json进行页面数据的组装
     *
     * @param json
     */

    private List<Group> convertDatas(String json) {

        List<Group> datas = new ArrayList<>();

        // 使用JSONObject来解析服务器返回的数据格式
        try {
            JSONObject jsonObject = new JSONObject(json);

            //获取服务器返回的组的信息的对象 team0-team9
            JSONObject teamlist = jsonObject.getJSONObject("classinfo").getJSONObject("teamlist");

            for (int i = 0; i < teamlist.length(); i++) {
                //获取每个组的数据
                JSONObject object = teamlist.getJSONObject("team"
                        + i);

                //服务器返回的该小组有信息时创建该小组的数据
                Group group = new Group();

                // 设置小组的名称
                group.name = object.getString("name");
                // 设置小组的music
                group.music = object.getString("music");
                // 设置小组的classNum
                group.classnum = object.getInt("classnum");
                // 设置小组的未知
                group.exp = object.getInt("exp");
                // 设置小组的icon
                group.icon = object.getInt("icon");
                // 设置小组的money
                group.money = object.getInt("money");
                // 设置小组的Num
                group.num = object.getInt("num");
                // 设置小组的标语
                group.slogan = object.getString("slogan");
                // 设置Taget
                group.taget = object.getString("taget");
                // 设置小组的Teamid
                group.teamID = object.getInt("teamID");
                // 设置小组的userID
                group.userID = object.getString("userID");

                //创建每个组的智勇欢爱四个学生的信息,默认添加四个
                List<StudentInfo> infos = new ArrayList<>();
                //根据服务器返回的智勇欢爱给默认创建的四个学生
                // 解析智wisdom 勇brave 欢joy 爱love 四个模型
                JSONObject wisdom = object.optJSONObject("wisdom");
                JSONObject brave = object.optJSONObject("brave");
                JSONObject joy = object.optJSONObject("joy");
                JSONObject love = object.optJSONObject("love");
                infos.add(getPerson(group.teamID + "", group.num, object.getInt("classnum") + "", wisdom));
                infos.add(getPerson(group.teamID + "", group.num, object.getInt("classnum") + "", brave));
                infos.add(getPerson(group.teamID + "", group.num, object.getInt("classnum") + "", joy));
                infos.add(getPerson(group.teamID + "", group.num, object.getInt("classnum") + "", love));
                group.persons = infos;
                datas.add(group);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return datas;
    }


    /**
     * 将一个JSONObject复制给PersonInfo对象
     */
    private StudentInfo getPerson(String teamId, int teamNum, String classNum, JSONObject object) {
        StudentInfo info = new StudentInfo();
        try {
            if (null != object) {
                //服务器返回的智勇欢爱不为空
                info.teamId = teamId;
                info.icon = object.getString("icon");
                info.birthday = object.getString("birthday");
                info.teamnum = object.getInt("teamnum");
                info.nickname = object.getString("nickname");
                info.tel = object.getString("tel");
                info.classnum = object.getInt("classnum");
                info.favorite = object.getString("favorite");
                info.id = object.getInt("id");
                info.userID = object.getString("userID");
                info.exp = object.getInt("exp");
                info.school = object.getString("school");
                info.address = object.getString("address");
                info.name = object.getString("name");
                info.money = object.getInt("money");
                info.gender = object.getString("gender");
                info.grade = object.getString("grade");
                info.payment = object.getString("payment");
                info.isDelete = false;
            } else {
                //服务器返回的智勇欢爱为空,默认给每个成员复制teamid,classnum
                info.teamId = teamId;
                info.teamnum = teamNum;
                info.classnum = Integer.parseInt(classNum);
                info.isDelete = false;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.lv_add_student, R.id.tv_class_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.lv_add_student:
                //点击事件,跳转到添加新学生的界面
                UiUtils.startActivity(this, TeacherAddStudentActivity.class);
                break;
            case R.id.tv_class_name:
                //修改班级名称
                showAddClassPop();
                break;
        }
    }

    /**
     * 添加修改班级的弹框
     */
    private void showAddClassPop() {
        TDialogManager.show(this, getSupportFragmentManager(), R.layout.pop_add_class, 0.3f, new OnBindViewListener() {
            @Override
            public void bindView(BindViewHolder viewHolder) {
                //班级头像
                ImageView lvClass = viewHolder.getView(R.id.lv_class);
                lvClass.setImageResource(classHeads[classInfo.getIcon() - 1]);
                EditText etInput = viewHolder.getView(R.id.et_input);
                etInput.setText(classInfo.getName());
                etInput.setFilters(new InputFilter[]{new MaxTextLengthFilter(11)});
            }
        }, new OnViewClickListener() {
            @Override
            public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                switch (view.getId()) {
                    case R.id.bt_save:
                        EditText etInput = viewHolder.getView(R.id.et_input);
                        String className = etInput.getText().toString().trim();
                        if (TextUtils.isEmpty(className)) {
                            ToastUtils.showShort("未输入班级名称");
                            return;
                        }

                        if (className.equals(classInfo.getName())) {
                            ToastUtils.showShort("未做修改,不需要保存");
                            return;
                        }

                        //请求服务器添加班级,添加成功后刷新界面
                        doUpdateClassNameAction(className);

                        //关闭弹框
                        TDialogManager.dismiss();
                        break;
                    case R.id.lv_close:
                        //关闭弹框
                        TDialogManager.dismiss();
                        break;
                }
            }
        }, R.id.bt_save, R.id.lv_close);
    }

    /**
     * 修改班级名称
     *
     * @param className
     */
    private void doUpdateClassNameAction(final String className) {
        TDialogManager.dismiss();
        CustomDialogManager.show(this, "修改中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "27");
        map.put("userID", AccountUtils.getAccount(this));
        map.put("icon", classInfo.getIcon() + "");
        map.put("name", className);
        map.put("num", classInfo.getNum() + "");

        HttpUtils.post(HttpAddress.UPDATECLASS, map, this, new HttpCallBack<Res>() {
            @Override
            public void onSuccess(Res res) {
                if (1 == res.getState()) {
                    //修改成功
                    ToastUtils.showShort("修改成功");
                    //通知TeacherMyClassAndGradActivity刷新
                    BusInfo busInfo = new BusInfo();
                    busInfo.type = TeacherMyClassAndGradeActivity.UPDATEPAGE;
                    EventBus.getDefault().post(busInfo);
                    //更新页面的班级名称
                    tvClassName.setText(className);
                    CustomDialogManager.dissmiss();
                }
            }

            @Override
            public void onError(String e) {
                ToastUtils.showShort(BaseApplication.ERROR);
                CustomDialogManager.dissmiss();
            }
        });

    }

    /**
     * 添加小组的操作
     * 先判断当前小组是否大于10个,如果大于10个不允许操作
     */
    private void addGroupAction() {
        if (oldDatas != null && oldDatas.size() >= 10) {
            ToastUtils.showShort("最多只能添加10个小组");
        } else {
            //先统计已经使用多小组头像和名称
            initHasUsedData();

            //跳转到创建小组的界面
            TeacherCreateGroupActivity.goActivity(this, usedIcons, usedNames, classNum);
        }
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.type == CREATEGROUPSUCCESS) {
            //创建小组成功,移除学生,添加学生成功请求服务器重启刷新该页面
            http(BqaManager.PULLREFRESH);
        }
    }
}
